﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Dazaza.Framework.Config
{
    /// <summary>
    /// 读取各种配置
    /// </summary>
    public class ConfigManager
    {
        private static readonly string CONNECTION_CONFIG_VIRTUAL_PATH = "/config/ConnectionConfig.config";
        private static readonly string CONNECTION_STRING_DEFAULT = "server=localhost;database=dazaza;user ID=sa;Trusted_Connection=SSPI;Pooling=true;min pool size=5;max pool size=180;";

        /// <summary>
        /// 相对路径转化成绝对路径
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private static string GetDiskPathByVirtualPath(string path)
        {
            if (string.IsNullOrEmpty(path) == false)
            {
                return System.Web.HttpContext.Current.Server.MapPath(path);
            }
            return string.Empty;
        }

        /// <summary>
        /// 获取数据库连接字符串（/config/connectionConfig.config ）
        /// </summary>
        /// <returns></returns>
        public static ConnectionConfig GetConnectionConfig()
        {
            string diskPath = GetDiskPathByVirtualPath(CONNECTION_CONFIG_VIRTUAL_PATH);

            //如果配置文件不存在，创建它
            //if (System.IO.File.Exists(diskPath) == false)
            //{
            //    Utility.SerializeHelper.SerializeToXml<ConnectionConfig>(new ConnectionConfig()
            //    {
            //        ConnectionConfigItems = new List<ConnectionConfigItem>() 
            //        { 
            //            new ConnectionConfigItem()
            //            { 
            //                Name="main", 
            //                ConnectionString=CONNECTION_STRING_DEFAULT
            //            },
            //            new ConnectionConfigItem()
            //            {
            //                Name="Readonly",
            //                ConnectionString=CONNECTION_STRING_DEFAULT
            //            }
            //        }
            //    }, diskPath);
            //}

            return Utility.SerializeHelper.DeSerializeXml<ConnectionConfig>(diskPath);
        }
    }
}
